<template>
  <van-popup
    v-model:show="cityShow"
    position="bottom">
    <van-picker
      v-model="selectedValues"
      :columns="areaList"
      :columns-field-names="customFieldName"
      @confirm="onConfirm"
      @cancel="cityShow = false" />
  </van-popup>
</template>

<script setup lang="ts">
import type { PickerColumn } from 'vant';
import common from '@/api/api-common';
import { ref, watch, nextTick } from 'vue';
import { getCompleteRegion } from '@utils/index';
import route from '@/router';
interface Props {
  region?: string;
  callback?: Function;
  remove?: Function;
}
const props = withDefaults(defineProps<Props>(), {
  region: '',
  callback: Function,
  remove: Function
});

const customFieldName = {
  text: 'name',
  value: 'region',
  children: 'sub'
};
const cityShow = ref(true);
const selectedValues = ref<any>();
watch(
  () => cityShow.value,
  (val) => {
    !val && props.remove();
  }
);
watch(
  () => props.region,
  (val) => {
    nextTick(() => {
      selectedValues.value = getCompleteRegion(val).split(',');
    });
  },
  {
    deep: true,
    immediate: true
  }
);
// 路由变化时关闭组件
watch(
  () => route,
  () => {
    cityShow.value = false;
    props.remove();
  },
  {
    deep: true
  }
);

const areaList = ref<PickerColumn>([]);

const cityList = () => {
  common.cityRegionModule({}).then((res: any) => {
    if (res.success) {
      res.data.forEach((item: any) => {
        if (item.name === '请选择') {
          item.sub = [
            {
              child: false,
              name: '请选择',
              region: null,
              sub: []
            }
          ];
        }
        if (item.sub.length) {
          item.sub.forEach((d: any) => {
            if (d.sub.length) {
              d.sub.forEach((s: any) => {
                delete s.sub;
              });
            }
          });
        }
      });
      areaList.value = res.data;
    }
  });
};
cityList();

type Params = {
  name: string;
  region: string;
};
const onConfirm = (val: any) => {
  const parmas: Params = {
    name: '',
    region: ''
  };
  console.log(val.selectedOptions);
  parmas.name = val.selectedOptions
    .map((item: any) => item?.region && item?.name)
    .filter((item: any) => item)
    .join('-');

  parmas.region = val.selectedValues.filter((item: any) => item).slice(-1)[0];
  typeof props.callback === 'function' && props.callback(parmas);
  cityShow.value = false;
};
</script>

<style lang="scss" scoped></style>
